package com.example.drugaiservice.common.utils;

import com.example.drugaiservice.pojo.entity.Hosp;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
@Component
public class HospitalCSV {
    public List<Hosp> HospCSV(Hosp hosp) {
        String csvFile = "src/main/resources/db/医院.csv";
        String line = "";
        String cvsSplitBy = ",";

        List<String[]> hospitalList = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
            while ((line = br.readLine()) != null) {
                String[] hospital = line.split(",", -1); // 使用负数参数保留末尾空字段
                hospitalList.add(hospital);
            }

            // 输入信息

            String sheng = hosp.getProvince();
            String shi = hosp.getCity();
            String name = "";
            String jianjie = "";
            String dizhi = "";
            String keshi = hosp.getDepartment();

            // 先按省份查找
            List<String[]> provinceResults = new ArrayList<>();
            for (String[] hospital : hospitalList) {
                if (containsKeyword(hospital, sheng)) {
                    provinceResults.add(hospital);
                }
            }

            // 在省份结果中按城市查找
            List<String[]> cityResults = new ArrayList<>();
            for (String[] hospital : provinceResults) {
                if (containsKeyword(hospital, shi)) {
                    cityResults.add(hospital);
                }
            }

            // 在城市结果中按其他条件模糊查询
            List<String[]> finalResults = new ArrayList<>();
            for (String[] hospital : cityResults) {
                if (containsKeyword(hospital, name) &&
                        containsKeyword(hospital, jianjie) &&
                        containsKeyword(hospital, dizhi) &&
                        containsKeyword(hospital, keshi)) {
                    finalResults.add(hospital);
                }
            }
            List<Hosp>lists=new ArrayList<>();
            // 输出结果
            System.out.println("查询结果：");
            for (String[] hospital : finalResults) {
                lists.add(Hosp.builder().province(hospital[0]).city(hospital[1]).name(hospital[2]).intro(hospital[3]).
                        addr(hospital[4]).department(hospital[5]).build());
            }
            return lists;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 检查字符串数组中是否有字段包含指定关键词
    private static boolean containsKeyword(String[] array, String keyword) {
        for (String element : array) {
            if (element.toLowerCase().contains(keyword.toLowerCase())) {
                return true;
            }
        }
        return false;
    }
}

